package com.bblocks.common.alarmnotice;

import com.bblocks.common.anti_reptile.constant.RuleResultEnum;
import com.bblocks.common.anti_reptile.module.MatchResult;
import com.bblocks.common.anti_reptile.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;


@Slf4j
public class AlarmMailNoticeService implements NoticeService {

    //template模板引擎
    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public void onLimiterEvent(final MatchResult matchResult) {
        if(RuleResultEnum.RATELIMIT_ALARM.getLockType().equals(matchResult.getMatchRule().getLockType())){

            log.info("资源：{}，涉嫌超限:{}，需要邮件通知!", matchResult.getUrl(),matchResult.getMatchRule().getRequestMaxSize());
            // 发送邮件
            log.warn("未实现~~");
        }
    }

    @Override
    public void onBlackOverEvent(final MatchResult matchResult) {
    }

    @Override
    public int getOrder() {
        return 10;
    }

    /*private void xx(){

        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            // 发送人的邮箱
            messageHelper.setFrom("359073594@qq.com");
            //发给谁  对方邮箱
            messageHelper.setTo("359073594@qq.com");
            //标题
            messageHelper.setSubject("测试邮件");
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("username","法外狂徒张三");
            List<User> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                User user = new User("list"+i,"而非留守",23+i);
                list.add(user);
            }
            map.put("listUser",list);
            map.put("img","../static/2.jpg");
            context.setVariables(map);
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("alarmMail.html",context); //指定模板路径

            messageHelper.setText(emailContent,true);
            //添加图片
            FileSystemResource file = new FileSystemResource(new File(Demo2.class.getResource("/static/2.jpg").getFile()));
            messageHelper.addInline("test001", file);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败");
        }
    }*/
}